/**
 * @file Describe the file
 * @author author-name: lihao 逻辑开发
 *         author-name2：lizhiguo(18792718848@163.com)代码优化
 */
(function ($, window){
		var AddDevice_2 = function(options) {
		this.options = $.extend(true, {
			  id: '__MUI_AddDevice_2',
		    }, options || {});
		    this.init();
		    this.initEvent();
	 };
   var imageUploadUrl = "http://app.xiaoweicanting.com/hospital.php?m=App&c=equipment&a=uploadImg";
	 var proto = AddDevice_2.prototype;
	    proto.init = function() {
          var self = this;
          this.state = {
              selectedDeviceType: '',
              deviceModel: '',
              DeviceName: '',
              DeviceArea: '',
              DeviceImgUrl: '',
              DeviceInf:'',
              DeviceImgUrlArr: [],
              imageFiles: [],
              modelId: '',
              tid: '',
              typeid: '',
              deviceTwo: '',
              deviceThree: '',
              deviceTid: '',
              equipmentFactoryOption: '',
              tmpDom: [],
              inputFocusId: '',
              baseUrl: 'https://bird.ioliu.cn/v1?url=http://app.xiaoweicanting.com/hospital.php',
              picPage: {  
                  imgUp: function(){  
                  //生成手机原生选择框ui
                      plus.nativeUI.actionSheet({cancel:"取消",buttons:[  
                         {title:"拍照"},  
                          {title:"从相册中选择"}  
                      ]}, function(e){//1 是拍照  2 从相册中选择  
                          switch(e.index){  
                            //拍照并显示
                              case 1: self.clickCamera();
                              break; 
                              //从相册选取
                              case 2: self.clickGallery();
                              break;  
                              default: 
                              //出错时
                              break; 
                          }  
                        });  
                  }  
                //摄像头  
              }
          }
      mui.previewImage();
	};
	proto.initEvent = function() {
      
      //声明一个对象用于记录监听的事件
      var nowListener=null;
        //声明对应的数组
		  var self = this;
      mui('.mui-scroll-wrapper').scroll();
		  $('.DeviceOwnership').on('tap', '#equipmentTypeOne', function() {
          // $("#DeviceName")[0].blur();
          
          self.judgePop(0);
       });
      
      $('.DeviceOwnership').on('tap', '#equipmentModel', function() {
          self.judgePop(1);
       });

      $('.DeviceOwnership').on('tap', '#equipmentTypeTwo', function() {
          self.judgePop(2);
       });
      $('.DeviceOwnership').on('tap', '#equipmentTypeThree', function() {
          self.judgePop(3);
       });
       $('.DeviceOwnership').on('tap', '#equipmentFactory', function() {
          self.judgePop(4);
       });
      mui('body').on('tap', '.mui-popover', function(e) {
      
          //当用户点击popover后隐藏popover
          mui('.mui-popover').popover('hide');
      
      });
      var self = this;
      
      //给设备名称input设置监听
      document.getElementById("DeviceName").addEventListener('input',function(){
          self.state.DeviceName = this.value;
          
          //检测是否所有的数据已经被赋值，若已经赋值，则改变按钮颜色，并使其可以点击
          self.judgeButton();
      },false);
      
      //给设备基本信息设置监听
      document.getElementById("textarea").addEventListener('input',function(){
          self.state.DeviceInf = this.value;
          self.judgeButton();
      },false);
        
      //给设备场地设置监听
      document.getElementById("DeviceArea").addEventListener('input',function(){
        self.state.DeviceArea = this.value;
          
          //检测是否所有的数据已经被赋值，若已经赋值，则改变按钮颜色，并使其可以点击
        self.judgeButton();
      },false);
      window.addEventListener("tap", function(e){
          var p;
          e = e || window.event;
          p = e.target;
          if (p.nodeName === "INPUT") {
             self.state.inputFocusId = p.id;    
          }
      }, false)
        //
      this.getDeviceInfo("deviceUlOne", "deviceTypeOne", "tid", "tid", "selectedDeviceType", 
                           this.state.baseUrl + "?m=App&c=equipment&a=getNewEquipmentTypeList_Level1&uid=3&token=dfaf",
                           this.getDeviceTwo
                          )
      
	};
/**
 * 函数描述
 *
 * @param {object} p1 弹出modal框的列表UL标签元素
 * @param {object} p2 请求到的数据源
 * @param {string} p3 modal框中每条数据源接口返回的id
 * @return {Object} 无
 */
  proto.creatChildDom = function(list, data, getId){
      var myLi;
      var myA;
      var textNode;
          //如果存在myli,则清除
      if (list.children.length > 0){
          for(var i = 0, len = list.children.length; i < len; i++)
              list.removeChild(list.children[0]);
      }
      for(var i = 0; i < data.length; i++){
          //创建li对象
          myLi = document.createElement("li");
          myLi.className = 'mui-table-view-cell';
          myLi.id = data[i][getId];
          //创建a对象
          myA = document.createElement("a");
          myA.className = 'mui-navigate-right';
          //创建文字数据
          textNode = document.createTextNode(data[i].name);
          myA.appendChild(textNode);
          myLi.appendChild(myA);
          list.appendChild(myLi); 
      }
	}
/**
 * 函数描述
 *
 * @param {string} p1 弹出modal框的列表UL标签的id
 * @param {string} p2 选择区域的a标签的id
 *     
 * @param {string} p3 modal框中每条数据源接口返回的id
 * @param {string} p4 modal框中被选择的数据的id
 * @param {string} p5 用户选择之后，每个输入框对应的值
 * @param {string} p6 请求的地址
 * @param {function} p7 回调函数，作为下一级的请求（可选）
 * @return {Object} 无
 */
  proto.getDeviceInfo = function(ulId, aId, liId, selectId, key, url1, callback){
      var self = this;
      var ulList = document.getElementById(ulId);
      var hasDataList;
      mui.get(url1, function(dataObject){
          DeviceTypeData = dataObject.data;
          if (DeviceTypeData.length > 0){
              hasDataList = true;
              //声明需要的ul和a和对应文字标签
              self.creatChildDom(ulList, DeviceTypeData, liId);
          
             //给生成的list添加监听(声明一个匿名赋值给nowListener并绑定)
              ulList.addEventListener('selected', nowListener = function(e) {
                  self.state[key] = e.detail.el ? e.detail.el.innerText : "";
            
                  document.getElementById(aId).innerText = self.state[key];
                  //当用户选择完后，点击上面的选项时，需要对之后的选择框进行初始化
                  self.clearInput(aId);
                  self.state[selectId] = e.detail.el.id;
                  //在选择好需要的类型后，传入选择类型的id和原url获取设备接口并生成新的dom
                  //如果有回调函数则开始下一个请求
                  if (callback){
                      self.func = callback;
                      self.func();
                  }
                  //当用户重新选择的时候，需要把之前删除的厂商节点和设备型号恢复
                  if(hasDataList && self.state.tmpDom && $(".unHideableInput").length){
                      for(var i = 0 ;i < self.state.tmpDom.length; i++){
                          $(".DeviceOwnership")[0].removeChild($(".unHideableInput")[0]);
                          $(".DeviceOwnership")[0].insertBefore(self.state.tmpDom[i], $("#deviceNameDiv")[0]);
                  }
                  self.state.tmpDom = [];
                }
              });
          }else{
              var a = $("#" + aId)[0];
              var parent = a.parentNode.parentNode;
              hasDataList = false;
              //对设备类型三进行处理隐藏
              for (var i = 0 ;i < 2 ;i++ ){
                  if (parent.classList.contains('hideable')){
                      parent.style.display = "none";
                      parent = parent.nextElementSibling;
                  //对厂家和设备型号进行处理,变为手动输入
                  }else if (parent.classList.contains('unHideable') && !self.state.tmpDom.length){
                      var deviceArr = [
                          {id: "equipmentFactoryOption", name: "厂家"},
                          {id: "deviceModel", name: "设备型号"}
                      ];
                      if(a.id == "deviceModel") {deviceArr.shift()}
                      self.insertDomEle(parent, deviceArr);
                  }
            }
            
          }  
      });
  }
  proto.getDeviceTwo = function(){
      this.getDeviceInfo("deviceUlTwo", "deviceTypeTwo", "tid", "typeid", "deviceTwo", 
                         this.state.baseUrl + "?m=App&c=equipment&a=getNewEquipmentTypeList_Level2" + "&tid=" + this.state.tid + "&uid=3&token=dfaf",
                         this.getDeviceThree                    
                          )
  }
  proto.getDeviceThree = function(){
      this.getDeviceInfo("deviceUlThree", "deviceTypeThree", "tid", "deviceTid", "deviceThree", 
                         this.state.baseUrl + "?m=App&c=equipment&a=getNewEquipmentTypeList_Level3&tid=" + this.state.typeid + "&uid=3&token=dfaf",
                         this.getDeviceFactory                    
                        )
  }
  proto.getDeviceFactory = function(){
      this.getDeviceInfo("deviceUIFactory", "equipmentFactoryOption", "fid", "factoryId", "equipmentFactoryOption", 
                         this.state.baseUrl + "?m=App&c=equipment&a=getNewEquipmentTypeFactoryList&tid=" + this.state.deviceTid + "&uid=3&token=dfaf",
                         this.getDeviceModel                    
                          )
  }
  proto.getDeviceModel = function(){
      this.getDeviceInfo("mianUl2", "deviceModel", "specid", "modelId", "deviceModel", 
                         this.state.baseUrl + "?m=App&c=equipment&a=getFactoryEquipmentSpecList&fid=" + this.state.factoryId + "&uid=3&token=dfaf",
                         this.getDetailDeviceInfo
                          )
  }
  proto.getDetailDeviceInfo = function(){
      this.getDeviceBasicInf(this.state.baseUrl + "?m=App&c=equipment&a=getFactoryEquipmentSpecInfo&fid=" + this.state.factoryId + "&sid=" + this.state.modelId + "&uid=3&token=dfaf")            

  }
  proto.judgeButton = function(){
      var self = this;
      var beSelected = false;
      if((self.state.selectedDeviceType != "")
          && (self.state.deviceModel != "")
          && (self.state.DeviceName != "")
          && (self.state.DeviceArea != "")
          // && (self.state.DeviceImgUrl != "")
          && (self.state.DeviceInf != "")){
              document.querySelector('.mui-btn').style.backgroundColor = "#498af7";
              document.querySelector('.mui-btn').addEventListener('click', this.onPress.bind(this), false);
              beSelected = true;
      }
      else{
        if (beSelected){
              document.querySelector('.mui-btn').removeEventListener('click', this.onPress.bind(this), false);
              document.querySelector('.mui-btn').style.backgroundColor="rgba(73, 138, 247, 0.3)";
              beSelected = false;
        }
        
      }
  }

  proto.judgeCant = function(){
      var self = this;
      if((self.state.selectedDeviceType == "")
          || (self.state.deviceModel == "")
          || (self.state.DeviceName == "")
          || (self.state.DeviceArea == "")
          // || (self.state.DeviceImgUrl == "")
          || (self.state.DeviceInf == "")){
              mui.toast('请在填写完毕后点击下一步');
          }
 }
  proto.creatImg = function(url, dom, type){
      var self = this;
      if(url == ""){
            return false;
        }
      if(self.state.DeviceImgUrlArr.length === 5){
          mui.toast('添加图片已至上限');
          return;
      }
       
      var divDom = document.createElement("div");
      var deletedDom = document.createElement("div");
      var imgDom = document.createElement("img");
      var textDom = document.createTextNode("x");
      divDom.className = 'largeMainDiv';
      deletedDom.className = 'largeMainDivDelet';
      imgDom.src = type == 1 ? "http://app.xiaoweicanting.com/" + url : "http://app.xiaoweicanting.com" + url.slice(1);
      self.state.DeviceImgUrlArr.push(imgDom.src);
      imgDom.setAttribute("data-preview-group", "1");
      imgDom.setAttribute("data-preview-src", "");
      
      deletedDom.appendChild(textDom);
      deletedDom.id  = self.state.DeviceImgUrlArr.length - 1;
      var fatherDom = document.getElementById(dom);
      var imagesLength = self.state.DeviceImgUrlArr.length;
      if (type === 1){
          fatherDom.style.width = 85 * imagesLength + "px";
          imgDom.className = 'largeMainImg2'; 
      }
      else{
          fatherDom.style.width = 75 * imagesLength + 82 + "px";
          imgDom.className = 'largeMainImg';
          divDom.appendChild(deletedDom);
        
      }
      divDom.appendChild(imgDom);
      fatherDom.appendChild(divDom);
      deletedDom.addEventListener('click', function(){
          var i = self.state.DeviceImgUrlArr.length;
          fatherDom.removeChild(divDom);
          self.state.DeviceImgUrlArr.splice(this.id, 1);
          fatherDom.style.width = 75 * imagesLength + 82 + "px";
      }, false);
  }
  proto.getDeviceBasicInf = function(url){
      var self = this;
      mui.get(url, function(dataObject){
          DeviceBasicData = dataObject.data;
          
          //给余下的所有信息进行赋值
          self.state.DeviceName = DeviceBasicData.name ? DeviceBasicData.name : "";
          self.state.DeviceArea = DeviceBasicData.productionlocation ? DeviceBasicData.productionlocation : "";
          //删除原先的设备照片节点
          var fatherDom = document.getElementById("myImgDiv");
          var child = fatherDom.childNodes;
          for (var i = child.length-1; i >= 0; i--){
              fatherDom.removeChild(child[i]);
          }
          //删除原先的所有保存的图片
          self.state.DeviceImgUrlArr.length = 0;
            //若服务器上存在图片，隐藏照相按钮
          if (DeviceBasicData.basepic){
              self.state.DeviceImgUrl = DeviceBasicData.basepic; 
              self.creatImg(self.state.DeviceImgUrl, "myImgDiv", 1);
              
          }
          else{
              self.defaultCamera();
          }
            //将DeviceImgUrl存入DeviceImgUrlArr数组中
            
            
          self.state.DeviceArea = DeviceBasicData.productionlocation ? DeviceBasicData.productionlocation : "";
          //删除原先的DeviceInf = DeviceBasicData.intro ? DeviceBasicData.intro : "";
          //给余下的dom节点进行赋值
          document.getElementById("DeviceName").value = self.state.DeviceName;
          document.getElementById("DeviceArea").value = self.state.DeviceArea;
          document.getElementById("textarea").value = self.state.DeviceInf;
        //在这里判定是否所有的数据都已经被填充了，如果都已经被填充了，就将按钮的颜色改变为可点击的使按钮可以点击
          self.judgeButton();
            
          });
  }
  proto.removeChildOfPop = function(list){
      for(var j = list.childNodes.length; j > 0; j--){
            list.removeChild(list.childNodes[0]);
          }
  }
  proto.judgePop = function(type){
      var self = this;
      self.removeBlur(self);
      switch(type){
          case 0:
             mui('#mainPopoverOne').popover('show');
              break;
          case 1:
              if (self.state.equipmentFactoryOption){
                  mui('#mainPopover2').popover('show');
              }
              break;
          case 2:
              if(self.state.selectedDeviceType){
                  mui('#mainPopoverTwo').popover('show');
              }
              break;
          case 3:
              if(self.state.deviceTwo){
                  mui('#mainPopoverThree').popover('show');
              }
              break;
          case 4:
              if(self.state.deviceThree){
                  mui('#mainPopoverFactory').popover('show');
              }
              break;
          default:
              break;
          }
  }
  proto.clickCamera = function(){
      var self = this;
      var cmr = plus.camera.getCamera();
          //摄像头支持像素
      var res = cmr.supportedImageResolutions[0];
          //支持的图片格式
      var fmt = cmr.supportedImageFormats[0];
          //拍照回掉函数
      cmr.captureImage(
          function(path){//拍照成功的情况下
              //从h5暂存数据区域得到想要的图片
              plus.io.resolveLocalFileSystemURL(path, function(entry){//在成功的情况下
                //显示刚拍摄好的照片
                  
                  self.compressImage(path);
                  // self.state.DeviceImgUrl = entry.toLocalURL();
                  // self.creatImg(self.state.DeviceImgUrl, "myImgDiv");
              },
              function(e){//在读取拍照文件失败的情况下
                  // outLine("读取拍照文件错误：" + e.message);
              });
          },
          function(err){//拍照失败的情况下
              // outLine(err.message);
            },
            {
                resolution: res,
                format: fmt
            }
          );
  }

  proto.defaultCamera = function(){
      var self = this;
      var getPhoto = document.createElement('img');
      getPhoto.className = "addImg";
      getPhoto.src = "../../images/drawable-hdpi/eq_add_pic.png";
      getPhoto.addEventListener('click', self.state.picPage.imgUp, false);
      document.getElementById("myImgDiv").appendChild(getPhoto);
  }

  proto.clickGallery = function(){
      var self = this;
      //调用打开相册的方法
      plus.gallery.pick(
          function(path){//获取成功的情况下
              
              plus.io.resolveLocalFileSystemURL(path, function(entry){
                  // self.state.DeviceImgUrl = entry.toLocalURL();
                  self.compressImage(path);
                  // self.creatImg(self.state.DeviceImgUrl, "myImgDiv");
              },
              function(e){//在读取拍照文件失败的情况下
                  // outLine("读取相册照片失误错误：" + e.message);
              });
          },
          function(err){//打开相册的情况下的情况下
              // outLine(err.message);
          },
              {}
          );
  }
  proto.onPress = function(){
      var self = this;
      var webViewData = plus.webview.currentWebview();
      mui.openWindow({
          url:'AddDevice_3.html',
          id:'AddDevice_3.html',
          extras:{
              Hospital: webViewData.Hospital,
              HospitalId: webViewData.HospitalId,
              Dep: webViewData.Dep,
              DepId: webViewData.DepId,
              People: webViewData.People,
              PeopleId: webViewData.PeopleId,
              modelId: self.state.modelId,
              tid: self.state.tid,
              DeviceType: self.state.selectedDeviceType,
              deviceTypeTwo: self.state.deviceTwo,
              deviceTypeThree: self.state.deviceThree,
              deviceFactoryInfo: self.state.equipmentFactoryOption,
              DeviceModel: self.state.deviceModel,
              DeviceInf: self.state.DeviceInf,
              DeviceName: self.state.DeviceName,
              DeviceArea: self.state.DeviceArea,
              basicImgURL: self.state.DeviceImgUrlArr
          },
          styles:{
              scrollIndicator: 'none'
          }

      });
  }

  proto.uploadImage = function(path) {
      var self = this;
      var uploader = plus.uploader.createUpload(imageUploadUrl, {
            method: "POST"
          }, function(upload, status) {
                // alert(upload.responseText);
                var data = JSON.parse(upload.responseText);
                if(data.state ==  "success") {
                    mui.toast("上传成功！");
                    self.clearZip();
                    plus.nativeUI.closeWaiting();
                    self.creatImg(data.url, "myImgDiv");
                } else {
                    mui.toast("上传失败！");
                }
      });
      // var name = "imageTmpNmae" + Math.random().toFixed(4);
      uploader.addFile(path, {key: "headimg"});
      uploader.addData("userid", "4");
      uploader.start();
  }

  proto.insertDomEle = function(parent, arr){
      for(var j = 0; j < arr.length; j++){
          var next_parent = parent.nextElementSibling;
          this.state.tmpDom.push(parent);
          $(".DeviceOwnership")[0].removeChild(parent); 
          var h3 = document.createElement("h3");
          var input = document.createElement("input");
          var div_h3 = document.createElement("div");
          var div_input = document.createElement("div");
          var div_parent = document.createElement("div");
          div_input.className = 'ownerShipMainInput';
          input.className = 'DeviceInput';
          div_parent.className = "ownerShipMain inputMain unHideableInput";
          input.placeholder = "请输入" + arr[j].name;
          input.id = arr[j].id;
          input.type = "text";
          h3.innerText = arr[j].name;
          div_h3.appendChild(h3);
          div_input.appendChild(input);
          div_parent.appendChild(div_h3);
          div_parent.appendChild(div_input);
          $(".DeviceOwnership")[0].insertBefore(div_parent, $("#deviceNameDiv")[0]);
          var self = this;
          //设置监听
          document.getElementById(arr[j].id).addEventListener('input',function(){
              self.state[this.id] = this.value;
              self.judgeButton();
          },false);
          parent = next_parent;
      }
    this.defaultCamera();
  }
  proto.clearInput = function(selectId){
      var len = $(".ownerShipMain").length;
      var a = $("#" + selectId)[0];
      var parent = a.parentNode.parentNode.nextElementSibling;
      for (var i = 0 ; i < len ; i ++){
          if (parent.classList.contains('popoverDevice')){
              parent.style.display = "block";
              parent.children[1].children[1].innerText = parent.children[0].children[0].innerText;
              parent = parent.nextElementSibling;
          }
          //输入框部分清除数值
          else if(parent.classList.contains('ownerShipMain')){
              var text = parent.children[0].children[0].innerText;
              var tmpEle = parent.children[1].children[0];
              if (tmpEle.id == "myImgDiv" && tmpEle.children.length > 0){
                  tmpEle.removeChild(tmpEle.children[0]);
              }
              tmpEle.value = "";
              tmpEle.setAttribute("placeholder", "请输入" + text);
              parent = parent.nextElementSibling;   
          }else{
              break;
          }
    }
  }
  proto.removeBlur = function(self) {
      // var self = this;
      if (self.state.inputFocusId){
          $("#"+ self.state.inputFocusId)[0].blur();
      }
  }
//压缩照片
  proto.compressImage = function(imagePath) {
      var self = this;
      // outSet("开始压缩图片：");
      var imageName = imagePath.substr(imagePath.lastIndexOf("/") + 1);
      plus.nativeUI.showWaiting();
      plus.zip.compressImage({
          src: imagePath,
          dst: "_doc/" + imageName,
          overwrite: true,
          quality: 10
      },
      function(zip){
          self.uploadImage(zip.target);
      },function(e){
          alert("压缩失败");
          plus.nativeUI.closeWaiting();
          // outLine("压缩图片失败: "+JSON.stringify(e));
      });
  }
//清除压缩之后的照片
  proto.clearZip = function (){
      plus.io.resolveLocalFileSystemURL( "_doc/", function(entry){
          entry.removeRecursively();
      });
  }
var AddDeviceApi = null;
$.AddDevice = function(options) {
    if (!AddDeviceApi) {
    	  AddDeviceApi = new AddDevice_2(options);
    }

    return AddDeviceApi;
};
	})(mui, window)
